<script setup>
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import SecondaryCard from '@/views/home-view/secondaryCard.vue'
import { getHomeBannerInfo, getHomeGraphInfo } from '@/api/home-view'
import { Message } from 'element-ui'
import { group, sum } from '@/utils/radash'
import axios from 'axios'

const props = defineProps({
  level: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['changeParamsById', 'changeParamsByType'])

const infoList = ref([
  {
    name: '区县总数',
    icon: 'region-home',
    color: 'rgb(238,247,254)',
    num: '0',
    rate: '',
  },
  {
    name: '街道总数',
    icon: 'street-home',
    color: 'rgb(233,254,239)',
    num: '0',
    rate: '',
  },
  {
    name: '社区总数',
    icon: 'community-home',
    color: 'rgb(232,245,254)',
    num: '0',
    rate: '',
  },
  {
    name: '小区总数',
    icon: 'residence-home',
    color: 'rgb(243,243,255)',
    num: '0',
    rate: '',
  },
  {
    name: '问题住房总数',
    icon: 'building-home',
    color: 'rgba(249,241,208,0.6)',
    num: '0',
    rate: '',
  },
  {
    name: '居民问卷总数',
    icon: 'satisfaction-home',
    color: 'rgb(240, 255, 245)',
    num: '0',
    rate: '',
  },
  {
    name: '其中定向问卷总数',
    icon: 'satisfactionSpecial-home',
    color: '#F0FFF0',
    num: '0',
    rate: '',
  },
])

const params = ref({
  regionId: '',
  streetId: '',
  communityId: '',
  type: 'community',
  level: '',
})

// 存储外部传递的参数，在切换类型时保持不变
let externalParams = {
  regionId: '',
  streetId: '',
  communityId: '',
  level: '',
}

// 标记是否通过类型切换调用了API
let isTypeChangeRequest = false

const totalChart = ref()

let chart = null

watch(
  () => totalChart.value,
  (val) => {
    if (!val) {
      if (chart) {
        chart.dispose()
        chart = null
      }
    }
  }
)
// 待提交 0
// 待审核 2
// 通过 -1
// 退回 1
// 参见getStatusInfo方法
let legendData = ['未填写', '待提交', '待审核', '通过', '退回', '通过率']
let data1 = [
  // { name: '当前', value: 7.5 },
  // { name: '2025', value: 8.1 },
  // { name: '2030', value: 7.6 },
]
let data2 = [
  // { name: '当前', value: 7.6 },
  // { name: '2025', value: 8.2 },
  // { name: '2030', value: 8.1 },
]
let data3 = [
  // { name: '当前', value: 7.7 },
  // { name: '2025', value: 8.3 },
  // { name: '2030', value: 7.9 },
]
let data4 = [
  // { name: '当前', value: 26 },
  // { name: '2025', value: 28 },
  // { name: '2030', value: 24 },
]
let data5 = [
  // { name: '当前', value: 26 },
  // { name: '2025', value: 28 },
  // { name: '2030', value: 24 },
]
const option = {
  color: [
    'rgb(230,230,230)',
    'rgb(252, 202, 0)',
    'rgb(56, 148, 255)',
    'rgb(2, 196, 86)',
    'rgba(255,5,5,1)',
  ],
  legend: {
    top: '2%',
    left: 'center',
    itemWidth: 10,
    itemHeight: 8,
    itemGap: 15,
    textStyle: {
      fontFamily: 'MicrosoftYaHei',
      fontSize: 12,
      color: 'black',
    },
    data: legendData,
    show: true,
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    formatter: (param) => {
      if (!Array.isArray(param) || param.length === 0) return ''
      
      const xName = param[0].name || ''

      if (params.value.type === 'myd') {
        // 只显示居民问卷和定向问卷的数据
        const seriesInfo = param
          .filter(item => item.seriesName === '居民问卷总数' || item.seriesName === '其中定向问卷总数')
          .map(item => `${item.marker} ${item.seriesName}：${item.value}`)
          .join('<br/>')
        return `<div style="margin-bottom: 5px;">${xName}</div>${seriesInfo}`
      }

      const seriesInfo = param
      .map(item => `${item.marker} ${item.seriesName}：${item.value}`)
      .join('<br/>')

      return `<div style="margin-bottom: 5px;">${xName}</div>${seriesInfo}`
    },
  },
  grid: {
    left: '1%',
    top: '10%',
    right: '1%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: ['渝中区', '渝北区', '南岸区'],
    interval: true,
    axisLine: {
      show: false,
    },
    splitLine: {
      show: false,
    },
    axisLabel: {
      show: true,
      margin: 14,
      fontFamily: 'MicrosoftYaHei',
      fontSize: 12,
      color: 'rgba(113, 113, 113, 1)',

      interval: 0,
      rotate: 40, //角度顺时针计算的
    },
    axisTick: {
      show: false,
    },
  },
  yAxis: [
    {
      type: 'value',
      name: '（个）',
      nameTextStyle: {
        fontFamily: 'PingFangSC-Regular, PingFang SC',
        fontSize: 12,
        color: '#999999',
      },
      axisLine: {
        show: false,
        lineStyle: {
          color: 'rgba(52, 51, 51, 1)',
        },
      },
      splitLine: {
        show: true,
      },
      axisLabel: {
        show: true,
        margin: 10,
        fontFamily: 'MicrosoftYaHei',
        fontSize: 12,
        color: 'rgba(113, 113, 113, 1)',
      },
      axisTick: {
        show: false,
      },
      minInterval: 1
    },
    // {
    //   type: 'value',
    //   name: '百分比',
    //   max: '100',
    //   nameTextStyle: {
    //     color: '#666666',
    //   },
    //   position: 'right',
    //   axisLine: {
    //     lineStyle: {
    //       color: '#cdd5e2',
    //     },
    //   },
    //   splitLine: {
    //     show: false,
    //   },
    //   axisLabel: {
    //     show: true,
    //     formatter: '{value} %', //右侧Y轴文字显示
    //     textStyle: {
    //       color: '#666666',
    //       fontSize: 14,
    //     },
    //   },
    // },
  ],
  series: [
    {
      name: legendData[0],
      type: 'bar',
      stack: 'truck',
      barWidth: 15,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 3,
        normal: {
          // label: {
          //   show: false,
          //   position: 'inside',
          //   // color: 'rgb(67, 234, 128)',
          //   color: '#fff',
          // },
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //   { offset: 0, color: 'rgba(56, 248, 212, .8)' },
          //   { offset: 1, color: 'rgba(67, 234, 128, .8)' },
          // ]),
        },
      },
      label: {
        show: false, // 默认不显示标签
        position: 'top',
        fontSize: 14,
        color: 'rgb(230,230,230)',
      },
      data: data5,
    },
    {
      name: legendData[1],
      type: 'bar',
      stack: 'truck',
      barWidth: 15,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 3,
        normal: {
          label: {
            // show: true,
            // position: 'inside',
            // // color: 'rgb(67, 234, 128)',
            // color: '#fff',
          },
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //   { offset: 0, color: 'rgba(56, 248, 212, .8)' },
          //   { offset: 1, color: 'rgba(67, 234, 128, .8)' },
          // ]),
        },
      },
      label: {
        show: false, // 默认不显示标签
        position: 'top',
        fontSize: 14,
        color: 'rgb(252, 202, 0)',
      },
      data: data2,
    },
    {
      name: legendData[2],
      type: 'bar',
      stack: 'truck',
      barWidth: 15,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 3,
        normal: {
          label: {
            // show: true,
            // position: 'inside',
            // // color: 'rgb(39, 39, 213)',
            // color: '#fff',
          },
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //   { offset: 0, color: 'rgba(39, 39, 213, .8)' },
          //   { offset: 1, color: 'rgba(136, 208, 207, .8)' },
          // ]),
        },
      },
      label: {
        show: false, // 默认不显示标签
        position: 'top',
        fontSize: 14,
        color: 'rgb(56, 148, 255)',
      },
      data: data1,
    },
    {
      name: legendData[3],
      type: 'bar',
      stack: 'truck',
      barWidth: 15,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 3,
        normal: {
          label: {
            // show: false,
            // position: 'inside',
            // // color: 'rgb(247, 114, 209)',
            // color: '#fff',
          },
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //   { offset: 0, color: 'rgba(247, 114, 209, .8)' },
          //   { offset: 1, color: 'rgba(200, 114, 242, .8)' },
          // ]),
        },
      },
      label: {
        show: false, // 默认不显示标签
        position: 'top',
        fontSize: 14,
        color: 'rgb(2, 196, 86)',
      },
      data: data3,
    },
    {
      name: legendData[4],
      type: 'bar',
      stack: 'truck',
      barWidth: 15,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 3,
        normal: {
          label: {
            // show: true,
            // position: 'inside',
            // // color: 'rgb(251, 169, 128)',
            // color: '#fff',
          },
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //   { offset: 0, color: 'rgba(251, 169, 128,.8)' },
          //   { offset: 1, color: 'rgba(247, 203, 107, .8)' },
          // ]),
        },
      },
      label: {
        show: false, // 默认不显示标签
        position: 'top',
        fontSize: 14,
        color: 'rgba(255,5,5,1)',
      },
      data: data4,
    },
    // {
    //   name: legendData[5],
    //   type: 'line',
    //   yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
    //   smooth: false, //平滑曲线显示
    //   symbol: 'circle', //标记的图形为实心圆
    //   symbolSize: 8, //标记的大小
    //   itemStyle: {
    //     normal: {
    //       color: '#72A9FE',
    //       borderColor: 'rgba(114, 169, 254, 0.5)', //圆点透明 边框
    //       borderWidth: 7,
    //     },
    //   },
    //   lineStyle: {
    //     color: '#72A9FE',
    //   },
    //   data: data5,
    // },
  ],
  // dataZoom: [
  //   {
  //     // 这是 dataZoom 的配置
  //     type: 'slider', // 使用 'slider' 类型的 dataZoom 组件
  //     start: 0, // 初始的起始百分比
  //     end: 50, // 初始的结束百分比
  //   },
  // ],
}

const clickChart = (item) => {
  // const id = item?.data?.id || ''
  // if (id) {
  //   emit('changeParamsById', id)
  // }
}

const changeLegend = (e) => {
  // myd 类型不处理复杂的图例选择逻辑，直接返回
  if (params.value.type === 'myd') {
    return
  }
  
  const { selected } = e
  // console.log(selected)
  const keys = Object.keys(selected)
  const enums = {
    待审核: 2,
    未填写: -2,
    通过: -1,
    退回: 1,
    待提交: 0,
  }
  const checkedKey = keys
    .filter((k) => k !== '通过率' && !selected[k])
    .map((k) => enums[k])
  const groupList = groupListTemp.value
  if (checkedKey.length === 5) {
    changeChartOption((a, b) => {
      const cur = groupList[a]
      const next = groupList[b]
      let curTotal = cur.find((i) => i.status === -2)?.total || 0
      let nextTotal = next.find((i) => i.status === -2)?.total || 0
      if (props.type === 'residence') {
        curTotal = sum(cur, (c) => {
          if (c.status === -2) {
            return 0
          }
          return c.total
        })
        nextTotal = sum(next, (n) => {
          if (n.status === -2) {
            return 0
          }
          return n.total
        })
      }
      return nextTotal - curTotal
    })
    // 确保图例显示状态正确
    option.legend.show = true
    chart.setOption(option)
  } else {
    changeChartOption((a, b) => {
      const cur = groupList[a]
      const next = groupList[b]
      let nextTotal = 0
      let curTotal = 0
      if (checkedKey.includes(-2)) {
        curTotal = sum(cur, (c) => {
          if (checkedKey.includes(c.status)) {
            return 0
          }
          return c.total
        })
        nextTotal = sum(next, (n) => {
          if (checkedKey.includes(n.status)) {
            return 0
          }
          return n.total
        })
      } else {
        curTotal = sum(cur, (c) => {
          if (checkedKey.includes(c.status)) {
            return 0
          }
          if (c.status === -2) {
            const item = cur.find((i) => i.status === -2)
            const others = cur.filter((i) => i.status !== -2)
            const othersCount = sum(others, (o) => o.total || 0)

            let value = item ? item.total - othersCount : 0
            if (props.type === 'residence') {
              value = 0
            }
            return value
          }
          return c.total
        })
        nextTotal = sum(next, (n) => {
          if (checkedKey.includes(n.status)) {
            return 0
          }
          if (n.status === -2) {
            const item = next.find((i) => i.status === -2)
            const others = next.filter((i) => i.status !== -2)
            const othersCount = sum(others, (o) => o.total || 0)

            let value = item ? item.total - othersCount : 0
            if (props.type === 'residence') {
              value = 0
            }
            return value
          }
          return n.total
        })
      }
      return nextTotal - curTotal
    })
    // 确保图例显示状态正确
    option.legend.show = true
    chart.setOption(option)
  }
}

const initChart = () => {
  if (totalChart.value) {
    chart = echarts.init(totalChart.value, 'light')
    chart.setOption(option)
    chart.on('click', clickChart)
    chart.on('legendselectchanged', changeLegend)
  }
}

const getBaseInfo = (params) => {
  getHomeBannerInfo(params).then((res) => {
    if (res.success) {
      if (res.data) {
        infoList.value.forEach((item) => {
          const key = item.icon.replace('-home', '')
          // if (key === 'building') {
          //   axios('buildingData.json').then((res) => {
          //     const data = res.data
          //     if (params.regionId) {
          //       const findItem = data.find((i) => i.pkid === params.regionId)
          //       if (findItem) {
          //         item.num = findItem.num
          //       } else {
          //         item.num = '-'
          //       }
          //     } else {
          //       item.num = data.reduce((prev, cur) => {
          //         return prev + cur.num
          //       }, 0)
          //     }
          //   })
          //   return
          // }
          const countKey = key + 'Count'
          const passKey = key + 'PassCount'
          item.num = res.data[countKey]
          item.rate = res.data[passKey]
          // const pass = res.data[passKey] ?? 0
          // const total = res.data[countKey]
          // item.rate = total ? ((pass / total) * 100).toFixed(2) : 100.0
        })
      }
    } else {
      Message.error(res.message)
    }
  })
}

const groupListTemp = ref([])

const changeChartOption = (compareFn) => {
  const groupList = groupListTemp.value
  const xData = Object.keys(groupList).sort(compareFn)
  option.xAxis.data = xData
  
  if (params.value.type === 'myd') {
    // myd 类型显示两个并排的柱状图：居民问卷和定向问卷
    const statusMinus2Series = option.series[0] // 居民问卷
    const status0Series = option.series[1]      // 定向问卷
    const status2Series = option.series[2]
    const statusMinus1Series = option.series[3]
    const status1Series = option.series[4]

    // 设置图例数据为居民问卷和定向问卷
    option.legend.data = ['居民问卷总数', '其中定向问卷总数']
    
    // 设置两个柱状图的颜色
    option.color[0] = 'rgb(200, 230, 210)' // 居民问卷颜色
    option.color[1] = 'rgb(255, 182, 193)' // 定向问卷颜色
    
    // 居民问卷数据 (count1)
    statusMinus2Series.name = '居民问卷总数'
    statusMinus2Series.stack = undefined // 不堆叠，并排显示
    statusMinus2Series.label = {
      show: true,
      position: 'top',
      fontSize: 14,
      color: 'rgb(200, 230, 210)', // 与柱子颜色一致
      formatter: function(params) {
        return params.value || '0'
      }
    }
    statusMinus2Series.data = xData.map((x) => {
      const items = groupList[x]
      let count1Value = 0
      if (items && items.length > 0) {
        const firstItem = items[0]
        count1Value = firstItem.count1 || firstItem.total || firstItem.count || firstItem.value || 0
        
        // 如果是数组且每个元素都有 count1，则求和
        if (count1Value === 0) {
          count1Value = items.reduce((sum, item) => {
            return sum + (item.count1 || item.total || item.count || item.value || 0)
          }, 0)
        }
      }
      
      return {
        name: x,
        id: items[0]?.id || '',
        value: count1Value,
        label: {
          show: true,
          position: 'top',
          color: 'rgb(200, 230, 210)', // 与柱子颜色一致
          formatter: count1Value || '0'
        }
      }
    })
    
    // 定向问卷数据 (count2)
    status0Series.name = '其中定向问卷总数'
    status0Series.stack = undefined // 不堆叠，并排显示
    status0Series.label = {
      show: true,
      position: 'top',
      fontSize: 14,
      color: 'rgb(255, 182, 193)', // 与柱子颜色一致
      formatter: function(params) {
        return params.value || '0'
      },
      showBackground: false,
      distance: 5
    }
    status0Series.data = xData.map((x) => {
      const items = groupList[x]
      let count2Value = 0
      if (items && items.length > 0) {
        const firstItem = items[0]
        count2Value = firstItem.count2 || 0
        
        // 如果是数组且每个元素都有 count2，则求和
        if (count2Value === 0) {
          count2Value = items.reduce((sum, item) => {
            return sum + (item.count2 || 0)
          }, 0)
        }
      }
      
      return {
        name: x,
        id: items[0]?.id || '',
        value: count2Value,
        label: {
          show: true,
          position: 'top',
          color: 'rgb(255, 182, 193)', // 与柱子颜色一致
          formatter: count2Value || '0'
        }
      }
    })
    
    // 清空其他系列的数据和标签
    status2Series.data = xData.map((x) => ({ name: x, id: '', value: 0 }))
    status2Series.label = { show: false }
    statusMinus1Series.data = xData.map((x) => ({ name: x, id: '', value: 0 }))
    statusMinus1Series.label = { show: false }
    status1Series.data = xData.map((x) => ({ name: x, id: '', value: 0 }))
    status1Series.label = { show: false }
  } else {
    // 非 myd 类型按原来的逻辑处理
    // 恢复原始图例数据
    option.legend.data = legendData
    
    // 恢复原始颜色设置
    option.color = [
      'rgb(230,230,230)',
      'rgb(252, 202, 0)',
      'rgb(56, 148, 255)',
      'rgb(2, 196, 86)',
      'rgba(255,5,5,1)',
    ]
    
    const statusMinus2Series = option.series[0]
    const status0Series = option.series[1]
    const status2Series = option.series[2]
    const statusMinus1Series = option.series[3]
    const status1Series = option.series[4]
    
    // 恢复堆叠设置
    statusMinus2Series.stack = 'truck'
    status0Series.stack = 'truck'
    status2Series.stack = 'truck'
    statusMinus1Series.stack = 'truck'
    status1Series.stack = 'truck'
    
    // 恢复系列名称
    statusMinus2Series.name = legendData[0]
    status0Series.name = legendData[1]
    status2Series.name = legendData[2]
    statusMinus1Series.name = legendData[3]
    status1Series.name = legendData[4]
    
    // 恢复标签设置 - 其他类型不显示标签
    statusMinus2Series.label = { show: false }
    status0Series.label = { show: false }
    status2Series.label = { show: false }
    statusMinus1Series.label = { show: false }
    status1Series.label = { show: false }
    // const passRateSeries = option.series[4]
    statusMinus2Series.data = xData.map((x) => {
      const item = groupList[x].find((i) => i.status === -2)
      const others = groupList[x].filter((i) => i.status !== -2)
      const othersCount = sum(others, (o) => o.total || 0)

      let value = item ? item.total - othersCount : 0
      if (props.type === 'residence') {
        value = 0
      }

      return {
        name: x,
        id: item?.id || '',
        value,
      }
    })
    status0Series.data = xData.map((x) => {
      const item = groupList[x].find((i) => i.status === 0)
      return {
        name: x,
        id: item?.id || '',
        value: item?.total || 0,
      }
    })
    status2Series.data = xData.map((x) => {
      const item = groupList[x].find((i) => i.status === 2)
      return {
        name: x,
        id: item?.id || '',
        value: item?.total || 0,
      }
    })
    statusMinus1Series.data = xData.map((x) => {
      const item = groupList[x].find((i) => i.status === -1)
      return {
        name: x,
        id: item?.id || '',
        value: item?.total || 0,
      }
    })
    status1Series.data = xData.map((x) => {
      const item = groupList[x].find((i) => i.status === 1)
      return {
        name: x,
        id: item?.id || '',
        value: item?.total || 0,
      }
    })
  }
  // passRateSeries.data = xData.map((x) => {
  //   const total = groupList[x].find((i) => i.status === -2)
  //   const pass = groupList[x].find((i) => i.status === -1)
  //   return {
  //     name: x,
  //     value: total
  //       ? total.total
  //         ? ((pass?.total ?? 0) / total.total) * 100
  //         : 0
  //       : 100,
  //   }
  // })
}

const getChartInfo = (params) => {
  if (params.level === '2' && params.type === 'street') {
    // console.log(22)
    return
  }
  getHomeGraphInfo(params).then((res) => {
    if (res.success && res.data) {
      const list =
        res.data?.filter((i) => !!i.name && !i.name.includes('测试')) || []
      groupListTemp.value = group(list, (f) => f.name)
      const groupList = groupListTemp.value
      changeChartOption((a, b) => {
        const cur = groupList[a]
        const next = groupList[b]
        
        if (params.type === 'myd') {
          // myd 类型比较 count1 + count2 的总和
          let curTotal = 0
          let nextTotal = 0
          
          if (cur && cur.length > 0) {
            const firstItem = cur[0]
            const count1 = firstItem.count1 || 0
            const count2 = firstItem.count2 || 0
            curTotal = count1 + count2
            
            // 如果是数组且每个元素都有数据，则求和
            if (curTotal === 0) {
              curTotal = cur.reduce((sum, item) => {
                const itemCount1 = item.count1 || 0
                const itemCount2 = item.count2 || 0
                return sum + itemCount1 + itemCount2
              }, 0)
            }
          }
          
          if (next && next.length > 0) {
            const firstItem = next[0]
            const count1 = firstItem.count1 || 0
            const count2 = firstItem.count2 || 0
            nextTotal = count1 + count2
            
            // 如果是数组且每个元素都有数据，则求和
            if (nextTotal === 0) {
              nextTotal = next.reduce((sum, item) => {
                const itemCount1 = item.count1 || 0
                const itemCount2 = item.count2 || 0
                return sum + itemCount1 + itemCount2
              }, 0)
            }
          }
          
          return nextTotal - curTotal
        } else {
          // 其他类型按原来的逻辑处理
          let curTotal = cur.find((i) => i.status === -2)?.total || 0
          let nextTotal = next.find((i) => i.status === -2)?.total || 0
          if (props.type === 'residence') {
            curTotal = sum(cur, (c) => {
              if (c.status === -2) {
                return 0
              }
              return c.total
            })
            nextTotal = sum(next, (n) => {
              if (n.status === -2) {
                return 0
              }
              return n.total
            })
          }
          return nextTotal - curTotal
        }
      })

      // 根据当前类型动态设置图例显示状态
      option.legend.show = true // 所有类型都显示图例
      
      // 对于 myd 类型，确保 y 轴设置合适
      if (params.type === 'myd') {
        option.yAxis[0].min = 0
        option.yAxis[0].minInterval = 1
      } else {
        // 恢复其他类型的 y 轴设置
        delete option.yAxis[0].min
        option.yAxis[0].minInterval = 1
      }

      if (totalChart.value) {
        if (!chart) {
          chart = echarts.init(totalChart.value, 'light')
          chart.on('click', clickChart)
          chart.on('legendselectchanged', changeLegend)
        }
        // chart.setOption(option)
      }
      chart.dispatchAction({
        type: 'legendAllSelect',
      })
      chart.setOption(option)
    } else {
      Message.error(res.message)
    }
  })
}

const handleRadioChange = () => {
  // 设置标记，表示通过类型切换调用了API
  isTypeChangeRequest = true
  
  // 切换类型时，保持外部传递的参数不变，只更新类型
  const newParams = {
    regionId: externalParams.regionId,
    streetId: externalParams.streetId,
    communityId: externalParams.communityId,
    level: externalParams.level,
    type: params.value.type
  }
  
  // 直接调用API，不更新externalParams
  getBaseInfo(newParams)
  getChartInfo(newParams)
  emit('changeParamsByType', params.value.type)
}

const inputData = (inputParams) => {
  
  // 更新外部参数存储
  externalParams = {
    regionId: inputParams.regionId || '',
    streetId: inputParams.streetId || '',
    communityId: inputParams.communityId || '',
    level: inputParams.level || '',
  }
  
  // 更新内部params，保持类型选择
  params.value = {
    ...externalParams,
    type: inputParams.type || params.value.type
  }
  
  // 如果已经通过类型切换调用了API，则重置标记并跳过
  if (isTypeChangeRequest) {
    isTypeChangeRequest = false
    return
  }
  
  // 总是调用API，除非是通过类型切换触发的
  getBaseInfo(params.value)
  getChartInfo(params.value)
}

defineExpose({
  inputData,
})

onMounted(() => {
  initChart()
  // 组件挂载时不自动调用inputData，等待父组件调用
  console.log('onMounted - externalParams:', externalParams)
  console.log('onMounted - params.value:', params.value)
})
</script>

<template>
  <div class="city-info">
    <div class="top-buttons">
      <template v-for="(item, index) in infoList">
        <div
          class="info-item"
          :style="{
            backgroundColor: item.color,
          }"
          :key="index"
          v-if="
            (item.icon === 'building-home' && Number(level) < 2) ||
            item.icon !== 'building-home'
          "
        >
          <div class="info-item-icon">
            <svg-icon :icon-class="item.icon==='satisfactionSpecial-home'?'satisfaction-home':item.icon" />
          </div>
          <div
            :class="[
              'info-item-text',
              item.icon === 'building-home' ? 'big' : '',
            ]"
          >
            <div class="info-item-name" :style="{width:item.icon==='satisfactionSpecial-home'||item.icon==='satisfaction-home'?'max-content':'100%'}">{{ item.name }}</div>
            <div class="info-item-num">{{ item.num }}</div>
          </div>
          <div class="info-item-rate" v-if="item.icon !== 'building-home' && item.icon !== 'satisfaction-home'&&item.icon !== 'satisfactionSpecial-home'">
            <span class="text">参与数：</span>{{ item.rate ?? '-' }}
          </div>
        </div>
      </template>
    </div>
    <div class="radio-group">
      <el-radio-group v-model="params.type" @change="handleRadioChange">
        <!-- <el-radio-button v-if="user.roleLevel !== 3" label="street"
          >街道信息</el-radio-button
        > -->
        <el-radio-button label="community">社区信息</el-radio-button>
        <el-radio-button label="residence">小区信息</el-radio-button>
        <el-radio-button label="myd">居民问卷</el-radio-button>
        <el-radio-button label="zf">问题楼栋</el-radio-button>
      </el-radio-group>
    </div>
    <secondary-card title="各区县数据采集进度统计" class="bottom-chart">
      <div
        class="placeholder"
        key="level"
        v-if="level === '2' && type === 'street'"
      >
        <el-empty description="暂无分析图表"></el-empty>
      </div>
      <div v-else class="chart" ref="totalChart"></div>
    </secondary-card>
  </div>
</template>

<style scoped lang="scss">
.city-info {
  height: 100%;
  width: 100%;

  .top-buttons {
    padding: 20px 30px;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;

    .info-item {
      box-sizing: border-box;
      //width: 230px;
      width: 280px;
      height: 93px;
      display: flex;
      align-items: center;
      padding: 14px;

      .info-item-icon {
        width: 42px;
        height: 42px;
        margin-right: 16px;
        font-size: 42px;
      }

      .info-item-text {
        width: 94px;
        display: flex;
        flex-direction: column;

        &.big {
          width: 130px;
        }

        .info-item-num {
          margin-top: 16px;
          height: 35px;
          font-family: AlibabaPuHui;
          font-size: 25px;
          font-weight: 500;
        }
      }

      .info-item-rate {
        height: 100%;
        display: flex;
        flex-direction: column;
        //align-items: flex-end;
        color: red;
        padding-top: 55px;

        .text {
          flex-shrink: 0;
          font-size: 12px;
          color: black;
        }
      }
    }
  }

  .radio-group {
    padding: 0 30px 20px 30px;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }

  .bottom-chart {
    width: calc(100% - 60px);
    height: calc(100% - 192px);

    .chart {
      height: 100%;
    }

    .placeholder {
      height: 100%;
    }
  }
}
</style>
